const path = require('path');
const WebpackVersionFile = require('dz-webpack-version-file')
// *************环境变量说明*******************
console.log('VUE_APP_ENV', process.env.VUE_APP_ENV); // front、client、server，用于webpack和前端分别针对客户端和服务端环境进行打包处理等
console.log('VUE_NODE_ENV', process.env.VUE_NODE_ENV); // 真正用来区分本地、开发环境、测试环境、生产环境各个配置项的条件
// process.env.NODE_ENV 通过defineplugin设置，值同isProduction，vue依据该环境变量决定是否比较客户端生成的虚拟DOM树是否与服务端渲染的DOM结构匹配

const isProduction = ['testmall', 'production'].includes(process.env.VUE_NODE_ENV); // isProduction 用于webpack压缩代码等
const publicDir = path.resolve(__dirname, '../Server/app/public/assets');

function resolve(dir) {
  return path.join(__dirname, dir);
}
module.exports = {
  lintOnSave: false,
  // productionSourceMap: false,
  publicPath: '/dz-mall/otc/front',
  outputDir: publicDir,
  // indexPath: path.resolve(__dirname, '../Server/app/view/index.ejs'),
  // babel-loader默认会忽略所有node_modules中的文件
  transpileDependencies: ['swiper', 'dom7', 'ssr-window', 'asn1', 'safer-buffer', 'asn1.js', 'bn.js', 'inherits', 'minimalistic-assert'], // android 4.x、ios 11 报错：Use of const in strict mode
  // transpileDependencies: [/node_modules/],
  configureWebpack: (config) => {
    return {
      entry: './src/main.js',
      // 对 bundle renderer 提供 source map 支持
      devtool: 'source-map',
      optimization: {
        splitChunks: {
          chunks: 'all', // chunks:哪些代码需要优化,all initial async
          minSize: 300000,
          minChunks: 1, // 被引用次数
          cacheGroups: { // 缓存组
            vendors: { // 项目基本框架等
              chunks: 'all',
              test: /(vue|vuex|vue-roter|vuex-router-sync|vant|vue-awesome-swiper|swiper)/,
              // test: node_modules
              name: 'vendors',
              priority: 100, // 缓存组打包的先后优先级
            },
            asynccommon: { // 异步加载公共包、组件等
              chunks: 'async',
              minChunks: 2,
              name: 'asynccommon',
              priority: 90,
            },
          }
        },
        minimize: isProduction,
      },
      plugins: [
        new WebpackVersionFile({
          output: path.resolve(__dirname, '../version/version.js'),
          package: './package.json',
          template: './version.ejs'
        })
      ]
    };
  },
  chainWebpack: config => {
    // config.module.noParse // eg.es6-promise 提高编译效果
    if (isProduction) {
      config.output.filename('js/[name].[contenthash:8].js').end();
      config.output.chunkFilename('js/[name].[contenthash:8].js').end();
    }

    config.plugin('define')
      .tap(args => {
      // args[0]['process.env'].NODE_ENV = isProduction ? 'production' : 'develpoment'; // 错误的写法
        args[0]['process.env'].NODE_ENV = JSON.stringify(isProduction ? 'production' : 'develpoment');
        args[0]['process.env'].VUE_NODE_ENV = JSON.stringify(process.env.VUE_NODE_ENV);
        return args;
      });

    // 设置别名
    // config.resolve.alias
    // .set("@", resolve("src"))
    // .set("assets", resolve("src/assets"))
    // .set("components", resolve("src/components"));

    // config.module
    // .rule('images')
    // .use('image-webpack-loader')
    // .loader('image-webpack-loader')
    // .options({ bypassOnDebug: true })
    // .end();

    config.plugins.delete('preload');
    config.plugins.delete('prefetch');

    // config.plugin('html')
    //   .tap(args => {
    //     args[0].title = '聚宝盆';
        
    //     args[0].meta = {
    //       keywords: '聚宝盆,聚宝盆,聚宝盆,',
    //       description: '聚宝盆,聚宝盆,聚宝盆,聚宝盆,聚宝盆,聚宝盆,聚宝盆,聚宝盆,聚宝盆,'
    //     };
    //     args[0].data = {
    //       userInfo: '<%-JSON.stringify(locals.userInfo)%>'
    //     };
    //     return args;
    //   });
  },
  css: {
    extract: { 
      filename: isProduction ? 'css/[name].[contenthash:8].css' : 'css/[name].css' ,
      chunkFilename: isProduction ? 'css/[name].[contenthash:8].css' : 'css/[name].css',
      ignoreOrder: true
    },
    loaderOptions: {
      less: {
        lessOptions: {
          modifyVars: {
            // 通过less文件覆盖
            hack: `true; @import "${resolve('src/assets/css/van-theme-reset.less')}";`
          }
        }
      }
    }
  },

  pluginOptions: {
    // 全局引入样式变量
    'style-resources-loader': {
      preProcessor: 'less',
      patterns: [resolve('src/assets/css/mixin.less')]
    }
  },

  // All options for webpack-dev-server are supported
  devServer: {
    open: false,
    port: 19002,
    https: false,
    hotOnly: false,
    proxy: {
      '/app/file': {
        // target: 'http://172.31.46.153:19999',
        target: 'http://172.31.46.168:8868/app/file',
        changeOrigin: true,
        pathRewrite: {
          '^/app/file': ''
        }
      },
      '/dz-mall/otc/front/api/dz-mall/r': {
        // target: 'http://172.31.46.153:19999',
        target: 'http://172.31.46.92:19299/dz-mall/r',
        changeOrigin: true,
        pathRewrite: {
          '^/dz-mall/otc/front/api/dz-mall/r': ''
        }
      },
    }
  }
};